Immutable classes include those for String, Boolean, Byte, Short, Integer, Long, Float, Double, and many others. The String class and all wrapper classes, in short, are immutable. By developing final classes with final data members, we can also create immutable classes.
Property Of Immutable class
The class instance variable is final, meaning that once an object has been created, its value cannot be changed.
Since the class is final, we are unable to create a subclass.
There are no setter methods, so there is no way to modify the instance variable's value.
Example: How to create Immutable class
// Java example to create Immutable class
finalclass Employee{
final String EmpId;
public Employee(String EmpId){
this.EmpId=EmpId;
}
public String EmpId(){
return EmpId;
}
}
publicclass Main {
publicstaticvoid main(String args[]){
Employee e = new Employee("45139562");
String s1 = e.EmpId();
System.out.println("Employee Id: " + s1);
}
}
Post your comment